﻿using System;
using System.Diagnostics;
using System.Collections.Generic;
//svnkit imports
using org.tmatesoft.svn.core;
using org.tmatesoft.svn.core.wc;

namespace Subsync.Core.Subversion
{
    class SVNUpdate : CommandBase
    {
        // Initialise variables with default settings.
        public long revision_no;
        public java.io.File wc_filepath;
        public SVNRevision revision = SVNRevision.HEAD;
        public SVNDepth depth = SVNDepth.INFINITY;
        public bool allowUnversionedObstruc = true;
        public bool depthIsSticky = true;

        // Minimal Constructor
		public SVNUpdate(string filepath) {
			Debug.WriteLine("SVNUpdate minimal Constructor with defaults");
			
            setupUpdate(filepath);
		}

        // Full Constructor
        public SVNUpdate(string filepath, SVNRevision rev, SVNDepth dep, bool allowobs, bool depthSticky)
        {
            Debug.WriteLine("SVNUpdate full Constructor");
            
            this.wc_filepath = new java.io.File(filepath);
            this.revision = rev;
            this.depth = dep;
            this.allowUnversionedObstruc = allowobs;
            this.depthIsSticky = depthSticky;
        }

        public void setupUpdate(string filepath)
        {
            this.wc_filepath = new java.io.File(filepath);
        }

        public override void Execute()
        {
            Debug.WriteLine("SVNUpdate Execution");

            //library setup
            Tools.setupLibrary();

            //load up the clients
            SVNClientManager cm = SVNClientManager.newInstance();

            try
            {
                revision_no = cm.getUpdateClient().doUpdate(wc_filepath, revision,
                        depth, allowUnversionedObstruc, depthIsSticky);
                Console.WriteLine("Updated to revision {0}", revision_no);
            }
            catch (SVNException e)
            {
                throw new SVNExecuteException(e.getMessage());
            }
        }

        public override Dictionary<string, List<object>> getTokens ()
		{
			Dictionary<string, List<object>> ret = new Dictionary<string, List<object>> ();
			ret.Add("update",new List<object>() {"ud","update"});
			return ret;
		}
		
		public override List<KeyValuePair<string,initPointer>> getInitPointers() {
			List<KeyValuePair<string,initPointer>> ret = new List<KeyValuePair<string,initPointer>>();
			ret.Add(new KeyValuePair<string,initPointer>("update",new initPointer(this.handleCLI)));
			return ret;
		}
		
		public void handleCLI(Dictionary<string,List<object>> tokens) {
			if (tokens["update"].Count != 1) {
				Console.WriteLine("Not enough arguments: Update requires at least 1 argument (filepath)");
				return;
			}
			string filepath = (string) tokens["update"][0];
			this.setupUpdate(filepath);
			this.Execute();
        }

        public SVNUpdate() {}
    }
}
